package com.company.dcm.server.protocol;

import com.company.dcm.utils.BinHexUtil;

import java.io.IOException;

/**
 * @Author: 王泽同
 * @Description:
 */
public class ProtocolMessageEncoder {

    private byte[] message;
    private int length;

    public ProtocolMessageEncoder(byte type){
        message = new byte[1024];
        message[0] = ProtocolConstant.START_MAGIC;
        message[1] = 1; // 版本号
        message[4] = type;
        length=0;
    }


    public boolean encode(byte[] buffer) throws IOException {
        try {
            System.arraycopy(buffer, 0, message, 5 + length, buffer.length);
            length += buffer.length;
        }catch (Exception e){
            return false;
        }

        return true;
    }

    public byte[] getMessage() {
        int tempLength = 5 + length;
        //setLengthToByteArray(length + 3);
        setLengthToByteArray(tempLength+3);//又说不补3
//        System.out.println("length: " + length);
        message[tempLength++]=0;
        message[tempLength++]=0;
        message[tempLength]=ProtocolConstant.END_MAGIC;

        byte[] result = new byte[length+8];
        System.arraycopy(message, 0, result, 0, length+8);
        return result;
    }

    private int getLengthFromByteArray(){
        return BinHexUtil.byteArrayToInt(message,2,4);
    }

    private void setLengthToByteArray(int length){
        message[2] = (byte) (length>>8);
        message[3] = (byte) (length & 255);
    }
}
